package cn.com.utils;

import java.security.SecureRandom;
import java.util.Base64;
import java.util.UUID;

/**
 * 密钥生成器
 *
 * @author LiuGuodong
 * @date 2024/01/08
 */
public class KeyGenerator {

    private static final int ACCESS_KEY_LENGTH = 20;  // 访问密钥AK长度
    private static final int SECRET_KEY_LENGTH = 40;  // 访问密钥SK长度

    /**
     * 生成AK
     *
     * @return {@link String}
     */
    public static String generateAccessKey() {
        String uniqueIdentifier = generateUniqueIdentifier();
        return generateRandomString(uniqueIdentifier, ACCESS_KEY_LENGTH);
    }

    /**
     * 生成SK
     *
     * @return {@link String}
     */
    public static String generateSecretKey() {
        String uniqueIdentifier = generateUniqueIdentifier();
        return generateRandomString(uniqueIdentifier, SECRET_KEY_LENGTH);
    }

    /**
     * 生成唯一标识符
     *
     * @return {@link String}
     */
    private static String generateUniqueIdentifier() {
        // 使用UUID和当前时间戳生成唯一标识符
        UUID uuid = UUID.randomUUID();
        long timestamp = System.currentTimeMillis();
        return uuid.toString() + timestamp;
    }

    /**
     * 生成随机字符串
     *
     * @param input  输入
     * @param length 长
     * @return {@link String}
     */
    private static String generateRandomString(String input, int length) {
        SecureRandom secureRandom = new SecureRandom(input.getBytes());
        StringBuilder randomString = new StringBuilder();
        while (randomString.length() < length) {
            byte[] randomBytes = new byte[1024];
            secureRandom.nextBytes(randomBytes);
            String encodedString = Base64.getUrlEncoder().withoutPadding().encodeToString(randomBytes);

            // 过滤掉非字母和数字字符
            for (char character : encodedString.toCharArray()) {
                if (Character.isLetterOrDigit(character)) {
                    randomString.append(character);
                    if (randomString.length() == length) {
                        break;
                    }
                }
            }
        }
        return randomString.toString();
    }

    public static void main(String[] args) {
        // 示例：生成并打印访问密钥和密钥
        String accessKey = generateAccessKey();
        String secretKey = generateSecretKey();

        System.out.println("Access Key: " + accessKey);
        System.out.println("Secret Key: " + secretKey);
    }
}
